﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;

namespace BookFinder
{
    public class BooksCollectionCleanUp
    {
        class AuthorInfo
        {
            public String _publisher { get; set; }
            public String _year { get; set; }
            public String _author { get; set; }
        }
        Hashtable isbnLookUp;

        public BooksCollectionCleanUp()
        {
            isbnLookUp = new Hashtable();
        }

        public void cleanUpCollectionList(ref BooksCollection bc)
        {
            this.mergeIsbnData(ref bc);
        }

        private void mergeIsbnData(ref BooksCollection bc)
        {
            foreach (Book book in bc)
            {
                AuthorInfo authorInfo;

                // All books in the collection should at least have an ISBN
                if ((book.ISBN != null && book.ISBN != "") && (book.Author != null || book.Publisher != null || book.Year != null))
                {
                    authorInfo = new AuthorInfo();
                    authorInfo._author = book.Author;
                    authorInfo._publisher = book.Publisher;
                    authorInfo._year = book.Year;

                    isbnLookUp[book.ISBN] = authorInfo;
                }
            }

            for(int i=0; i< bc.Count; i++)
            {
                Book book = bc[i];
 
                if ((book.ISBN != null && book.ISBN != "") && (book.Author == null || book.Publisher == null || book.Year == null))
                {
                    AuthorInfo authorInfo = (AuthorInfo)isbnLookUp[book.ISBN];
                    if (authorInfo != null)
                    {
                        book.Author = authorInfo._author;
                        book.Year = authorInfo._year;
                        book.Publisher = authorInfo._publisher;
                    }
                }

            }
        }
    }
}